<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 08.12.2014
 * Time: 15:28
 */

namespace Messenger\Messages;


use Messenger\Groups;
use Messenger\Queue;

class SetAllAsReadAction extends \Action {

	public function privileges()
	{
		return ['#authorized'];
	}

	public static function pullParams()
	{
		return ['identity'];
	}

	/**
	 * Отмечает все сообщения в группе, адресованные авторизованному пользователю, как прочитанные.
	 */
	protected function run()
	{
		$this->response->noCache(true);
		$this->response->noRender(true);

		$myProfileId = $this->request->_identity;
		$groupId = $this->request->groupId;

		/** @var Groups $groupModel */
		$groupModel = Groups::find($groupId);

		if (!$groupModel) {
			throw new \Exception("Group '$groupId' not found.", 404);
		}

		if (!isset($groupModel->relations[$myProfileId])) {
			throw new \Exception("Group '$groupId' hasn`t relation with user '$myProfileId'.", 404);
		}

		$unseenCount = $groupModel->unseenMessages[$myProfileId]->count;

		if ($unseenCount > 0) {
			$groupModel->unseenMessages[$myProfileId]->count = 0;
			$groupModel->save();

			Queue::enqueue(
				[
					'type' => \MessengerNotificationDeliveryConfig::TYPE_MESSAGE_READ,
					'data' => [
						'groupId' => (string)$groupId,
						'authorId' => null,
						'readerId' => (string)$myProfileId,
						'readTimestamp' => time(),
					],
				]
			);
		}
	}
}